package org.sauceggplant.item.man.ui.panel;

import com.alibaba.fastjson2.JSON;
import org.apache.commons.lang3.StringUtils;
import org.sauceggplant.item.man.dto.ItemDto;
import org.sauceggplant.item.man.dto.TypeDto;
import org.sauceggplant.item.man.po.Item;
import org.sauceggplant.item.man.po.Type;
import org.sauceggplant.item.man.service.ItemService;
import org.sauceggplant.item.man.service.TypeService;
import org.sauceggplant.item.man.service.impl.ItemServiceImpl;
import org.sauceggplant.item.man.service.impl.TypeServiceImpl;
import org.sauceggplant.item.man.ui.frame.MainFrame;
import org.sauceggplant.item.man.ui.table.DataTable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;

public class ItemPanel extends JPanel {

    private static final Logger logger = LoggerFactory.getLogger(ItemPanel.class);

    private MainFrame frame;

    private DataTable dataTable;

    private CardPanel cardPanel;

    private ItemService itemService = new ItemServiceImpl();

    private TypeService typeService = new TypeServiceImpl();

    private JComboBox typeComboBox = new JComboBox();

    private JTextField nameField = new JTextField(15);

    private JTextField countField = new JTextField(15);

    private JTextField remarkField = new JTextField(15);

    private JTextField queryParamValue;

    private Item item;

    private List<Item> itemList;

    private List<Type> typeList;

    private int columnLength = 5;

    private String[] columnNames = new String[]{"序号", "类别", "名称", "数量", "备注"};

    public ItemPanel(MainFrame frame) {
        this.frame = frame;
        init();
    }

    private void init() {
        this.setLayout(new BorderLayout());
        initData();
        JScrollPane pane = new JScrollPane(dataTable);
        pane.setBorder(new TitledBorder(new EmptyBorder(5, 5, 5, 5), ""));
        this.add(pane, BorderLayout.CENTER);
        JLabel typeLabel = new JLabel("类别", SwingConstants.RIGHT);
        JLabel nameLabel = new JLabel("名称", SwingConstants.RIGHT);
        JLabel countLabel = new JLabel("数量", SwingConstants.RIGHT);
        JLabel remarkLabel = new JLabel("备注", SwingConstants.RIGHT);
        typeComboBox.setPreferredSize(new Dimension((int) nameField.getPreferredSize().getWidth(), (int) typeComboBox.getPreferredSize().getHeight()));
        Component[][] rowData = new Component[][]{
                {
                        typeLabel,
                        typeComboBox,
                        nameLabel,
                        nameField,
                        countLabel,
                        countField,
                        remarkLabel,
                        remarkField
                }
        };
        cardPanel = new CardPanel(rowData, new JLabel("物品名称"));
        queryParamValue = cardPanel.getQueryParamValue();
        cardPanel.getQuery().addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                refreshTable(loadData(queryParamValue.getText()));
            }
        });
        cardPanel.getAdd().addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                item = new Item();
                item.setTypeId(getTypeByName(String.valueOf(typeComboBox.getSelectedItem())));
                item.setName(nameField.getText());
                item.setCount(countField.getText());
                item.setRemark(remarkField.getText());
                itemService.insert(item);
                refreshTable(loadData(queryParamValue.getText()));
            }
        });
        cardPanel.getSave().addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (null == item) {
                    JOptionPane.showMessageDialog(cardPanel, "请选择一行数据进行更改", "温馨提示", JOptionPane.WARNING_MESSAGE);
                } else {
                    item.setTypeId(getTypeByName(String.valueOf(typeComboBox.getSelectedItem())));
                    item.setName(nameField.getText());
                    item.setCount(countField.getText());
                    item.setRemark(remarkField.getText());
                    itemService.update(item);
                    refreshTable(loadData(queryParamValue.getText()));
                }
            }
        });
        cardPanel.getDelete().addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (null == item) {
                    JOptionPane.showMessageDialog(cardPanel, "请选择一行数据进行删除", "温馨提示", JOptionPane.WARNING_MESSAGE);
                } else {
                    itemService.delete(item.getId());
                    refreshTable(loadData(queryParamValue.getText()));
                }
            }
        });
        this.add(cardPanel, BorderLayout.NORTH);
    }

    private void initData() {
        String queryParam;
        if (null == queryParamValue) {
            queryParam = "";
        } else {
            queryParam = queryParamValue.getText();
        }
        Object[][] rowData = loadData(queryParam);
        dataTable = new DataTable(rowData, columnNames, frame);
        dataTable.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                int selectedRow = dataTable.getSelectedRow();
                if (selectedRow > -1 && selectedRow < itemList.size()) {
                    item = itemList.get(selectedRow);
                    String selectValue = getType(item.getTypeId());
                    if ("".equals(selectValue)) {
                        typeComboBox.setSelectedItem(null);
                    } else {
                        typeComboBox.setSelectedItem(selectValue);
                    }
                    nameField.setText(itemList.get(selectedRow).getName());
                    countField.setText(itemList.get(selectedRow).getCount());
                    remarkField.setText(itemList.get(selectedRow).getRemark());
                }
            }
        });
    }

    public void loadComboBox() {
        typeComboBox.removeAllItems();
        for (Type type : typeList) {
            typeComboBox.addItem(type.getName());
        }
    }

    public void refreshTable(Object[][] rowData) {
        DefaultTableModel tableModel = new DefaultTableModel(rowData.length, columnLength);
        for (int i = 0; i < rowData.length; i++) {
            for (int j = 0; j < columnLength; j++) {
                tableModel.setValueAt(rowData[i][j], i, j);
            }
        }
        tableModel.setColumnIdentifiers(columnNames);
        dataTable.setModel(tableModel);
        dataTable.updateUI();
    }

    public void loadType() {
        TypeDto typeDto = new TypeDto();
        typeDto.setOffset(0L);
        typeDto.setSize(100000L);
        typeDto.setOrder("`updateTime desc`");
        typeList = typeService.findAll(typeDto);
    }

    public Object[][] loadData(String queryParamValue) {
        ItemDto itemDto = new ItemDto();
        itemDto.setOffset(0L);
        itemDto.setSize(100000L);
        if (StringUtils.isNoneBlank(queryParamValue)) {
            itemDto.setNameIsLike(queryParamValue);
        }
        itemDto.setOrder("`name asc`");
        itemList = itemService.findAll(itemDto);
        logger.info(JSON.toJSONString(itemList));
        loadType();
        loadComboBox();
        Object[][] rowData = new Object[itemList.size()][columnLength];
        for (int index = 0; index < itemList.size(); index++) {
            Item item = itemList.get(index);
            rowData[index][0] = CardPanel.getIndex(index + 1);
            rowData[index][1] = getType(item.getTypeId());
            rowData[index][2] = item.getName();
            rowData[index][3] = item.getCount();
            rowData[index][4] = item.getRemark();
        }
        return rowData;
    }

    private String getType(Long id) {
        for (Type type : typeList) {
            if (type.getId() == (long)id) {
                return type.getName();
            }
        }
        return "";
    }

    private Long getTypeByName(String name) {
        for (Type type : typeList) {
            if (type.getName().equals(name)) {
                return type.getId();
            }
        }
        return 0L;
    }

    public JTextField getQueryParamValue() {
        return queryParamValue;
    }
}
